/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android framework
 * Create Time: 16-2-16 下午6:52
 */

package com.lenovo.framework.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.framework.R;


public class ContentLoaderView extends FrameLayout implements View.OnClickListener {
    public static final int LOAD_MORE_ITEM_SLOP = 4;
    View loadingView;
    View emptyView;
    View errorView;

    ImageView emptyImage;
    Button emptyRetryBtn;
    Button errorRetryBtn;
    TextView emptyMessageTV;
    TextView errorMessageTV;
    ImageView loadingIV;

    RecyclerView recyclerView;
    private View contentView;

    private OnRefreshListener refreshListener;
    private OnMoreListener moreListener;

    private boolean loadMore = false;
    private int totalPage = 1;
    private int currentPage = 1;
    private int fragmentType = -1;
    private static final int FRAGMENT_GRABORDERS = 0;
    private static final int FRAGMENT_RECEIVEORDERS = 1;
    private static final int FRAGMENT_ACTIVORDERS = 2;
    private static final int FRAGMENT_HISTORYORDERS = 4;
    private static final int FRAGMENT_MESSAGE = 5;

    private int padding;
    private int paddingLeft;
    private int paddingRight;
    private int paddingTop;
    private int paddingBottom;
    private boolean clipToPadding;

    public static final String DISPLAY_STATE = "display_state";
    public static final int STATE_CONTENT = 0x1;
    public static final int STATE_LOADING = 0x2;
    public static final int STATE_EMPTY = 0x3;
    public static final int STATE_ERROR = 0x4;
    private int displayState = STATE_LOADING;

    public ContentLoaderView(Context context) {
        super(context);
        initViews();
    }

    public ContentLoaderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
        initViews();
    }

    public ContentLoaderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(context, attrs);
        initViews();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ContentLoaderView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    private void initAttrs(Context ctx, AttributeSet attr) {
        TypedArray ta = ctx.obtainStyledAttributes(attr, R.styleable.ContentLoaderView);
        padding = ta.getDimensionPixelSize(R.styleable.ContentLoaderView_android_padding, -1);
        paddingLeft = ta.getDimensionPixelSize(R.styleable.ContentLoaderView_android_paddingLeft, -1);
        paddingRight = ta.getDimensionPixelSize(R.styleable.ContentLoaderView_android_paddingRight, -1);
        paddingTop = ta.getDimensionPixelSize(R.styleable.ContentLoaderView_android_paddingTop, -1);
        paddingBottom = ta.getDimensionPixelSize(R.styleable.ContentLoaderView_android_paddingBottom, -1);
        clipToPadding = ta.getBoolean(R.styleable.ContentLoaderView_android_clipToPadding, true);
        ta.recycle();
    }

    private void initViews() {
        inflate(getContext(), R.layout.list, this);
        setPadding(0, 0, 0, 0);
        setClickable(true);
        errorView = findViewById(R.id.error_view);
        emptyView = findViewById(R.id.empty_view);
        loadingIV = (ImageView) findViewById(R.id.iv_loading_running_gear);
        loadingView = findViewById(R.id.loading_view);
        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        errorRetryBtn = (Button) findViewById(R.id.btn_error_retry);
        errorMessageTV = (TextView) findViewById(R.id.error_message);
        emptyRetryBtn = (Button) findViewById(R.id.btn_empty_retry);
        emptyMessageTV = (TextView) findViewById(R.id.empty_message);
        emptyImage = (ImageView) findViewById(R.id.empty_emotion_no_order);

        errorRetryBtn.setOnClickListener(this);
        emptyRetryBtn.setOnClickListener(this);
        contentView = recyclerView;
        recyclerView.setOnScrollListener(mRecyclerScrollListener);
        if (padding != -1) {
            recyclerView.setPadding(padding, padding, padding, padding);
        } else {
            recyclerView.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
        }
        recyclerView.setClipToPadding(clipToPadding);
        setDisplayState(STATE_LOADING, fragmentType);
    }

    RecyclerView.OnScrollListener mRecyclerScrollListener = new RecyclerView.OnScrollListener() {
        int totalItemCount;
        int visibleItemCount;
        int firstVisibleItemPosition;

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            RecyclerView.LayoutManager layoutManager;
            layoutManager = recyclerView.getLayoutManager();
            totalItemCount = layoutManager.getItemCount();
            visibleItemCount = layoutManager.getChildCount();
            View firstVisibleChild = recyclerView.getChildAt(0);
            firstVisibleItemPosition = recyclerView.getChildLayoutPosition(firstVisibleChild);
            if (totalPage > currentPage &&
                    !loadMore &&
                    (firstVisibleItemPosition + visibleItemCount + LOAD_MORE_ITEM_SLOP) >= totalItemCount) {

                loadMore = true;
                if (moreListener != null) {
                    moreListener.onMore(++currentPage);
                }
            }
        }
    };

    public void setAdapter(final RecyclerView.Adapter adapter, int FragmentType) {
        fragmentType = FragmentType;
        recyclerView.setAdapter(adapter);
        if (adapter.getItemCount() > 0) {
            setDisplayState(STATE_CONTENT,fragmentType);
        }
        adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                update();
            }

            @Override
            public void onItemRangeChanged(int positionStart, int itemCount) {
                super.onItemRangeChanged(positionStart, itemCount);
                update();
            }

            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                update();
            }

            @Override
            public void onItemRangeRemoved(int positionStart, int itemCount) {
                super.onItemRangeRemoved(positionStart, itemCount);
                update();
            }

            @Override
            public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
                super.onItemRangeMoved(fromPosition, toPosition, itemCount);
                update();
            }

            private void update() {
                int itemCount = recyclerView.getLayoutManager().getItemCount();
                itemCount -= 2;//因为有header 还有 footer 啊
                if (itemCount > 0) {
                    if (loadMore) {
                        loadMoreCompleted();
                    }
                    setDisplayState(STATE_CONTENT, fragmentType);
                } else {
                    setDisplayState(STATE_EMPTY, fragmentType);
                }
                /*if (refreshLayout.isRefreshing()) {
                    refreshLayout.setRefreshing(false);
                }*/
            }
        });
    }

    /*public void setAdapter(final RecyclerView.Adapter adapter) {
        Log.e("LEE", "setAdapter " + adapter.getItemCount());
        recyclerView.setAdapter(adapter);
        if (adapter.getItemCount() > 0) {
            setDisplayState(STATE_CONTENT);
        }
        adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                Log.e("LEE", "setAdapter onChanged");
                update();
            }

            @Override
            public void onItemRangeChanged(int positionStart, int itemCount) {
                super.onItemRangeChanged(positionStart, itemCount);
                Log.e("LEE", "setAdapter onItemRangeChanged");
                update();
            }

            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                Log.e("LEE", "setAdapter onItemRangeInserted");
                update();
            }

            @Override
            public void onItemRangeRemoved(int positionStart, int itemCount) {
                super.onItemRangeRemoved(positionStart, itemCount);
                Log.e("LEE", "setAdapter onItemRangeRemoved");
                update();
            }

            @Override
            public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
                super.onItemRangeMoved(fromPosition, toPosition, itemCount);
                Log.e("LEE", "setAdapter onItemRangeMoved");
                update();
            }

            private void update() {
                int itemCount = recyclerView.getLayoutManager().getItemCount();
                itemCount -= 2;//因为有header 还有 footer 啊
                Log.e("LEE", "itemCount = " + itemCount);
                if (itemCount > 0) {
                    if (loadMore) {
                        loadMoreCompleted();
                    }
                    setDisplayState(STATE_CONTENT);
                } else {
                    setDisplayState(STATE_EMPTY);
                }
                *//*if (refreshLayout.isRefreshing()) {
                    refreshLayout.setRefreshing(false);
                }*//*
            }
        });
    }*/

    //@OnClick(R.id.btn_empty_retry)
    public void onRetryButtonClick() {
        setDisplayState(STATE_CONTENT, fragmentType);
        if (refreshListener != null) {
            refreshListener.onRefresh(false);
        }
    }

    public void notifyLoadFailed(Throwable error) {
        loadMore = false;
        if (currentPage == 1 && recyclerView.getLayoutManager().getChildCount() == 0) {
            //errorMessageTV.setText(error == null ? getResources().getString(R.string.unknown_error) : error.getMessage());
            setDisplayState(STATE_ERROR, fragmentType);
        } else {
            setDisplayState(STATE_CONTENT, fragmentType);
            Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void loadMoreCompleted() {
        loadMore = false;
        setDisplayState(STATE_CONTENT, fragmentType);
    }

    public void setMoreListener(OnMoreListener moreListener) {
        this.moreListener = moreListener;
    }

    public void setPage(int currentPage, int totalPage) {
        this.currentPage = currentPage;
        this.totalPage = totalPage;
    }

    private void setDisplayState(int state, int type) {
        this.displayState = state;
        //STATE_CONTENT 1
        //STATE_LOADING 2
        //STATE_EMPTY 3
        //STATE_ERROR 4
        AnimationDrawable animationDrawable = (AnimationDrawable) loadingIV.getBackground();
        if(state == STATE_LOADING){
            if(loadingView != null)
            loadingView.setVisibility(VISIBLE);
            if(animationDrawable != null)
                animationDrawable.start();
        }else{
            if(animationDrawable != null)
                animationDrawable.stop();
        }
        if (loadingView != null) {
            loadingView.setVisibility(state == STATE_LOADING ? VISIBLE : GONE);
        }
        errorView.setVisibility(state == STATE_ERROR ? VISIBLE : GONE);
        contentView.setVisibility(state == STATE_CONTENT ? VISIBLE : GONE);
        //加载的内容为空，再判断fragment的类型
        if(state == STATE_EMPTY){
            emptyView.setVisibility(View.VISIBLE);
            switch (type){
                case FRAGMENT_GRABORDERS:
                    emptyMessageTV.setText(R.string.grab_nothing);
                    emptyImage.setImageResource(R.drawable.icon_grab_nothing);
                    break;
                case FRAGMENT_RECEIVEORDERS:
                    emptyMessageTV.setText(R.string.nothing);
                    emptyImage.setImageResource(R.drawable.order_empty);
                    break;
                case FRAGMENT_ACTIVORDERS:
                    emptyMessageTV.setText(R.string.active_nothing);
                    emptyImage.setImageResource(R.drawable.icon_order_done);
                    break;
                case FRAGMENT_HISTORYORDERS:
                    emptyMessageTV.setText(R.string.nothing);
                    emptyImage.setImageResource(R.drawable.order_empty);
                    break;
                case FRAGMENT_MESSAGE:
                    emptyMessageTV.setText(R.string.msg_nothing);
                    emptyImage.setImageResource(R.drawable.order_empty);
                    break;
            }
        }else{
            emptyView.setVisibility(View.GONE);
        }
        //emptyView.setVisibility(state == STATE_EMPTY ? VISIBLE : GONE);
    }

    public void setOnRefreshListener(OnRefreshListener refreshListener) {
        this.refreshListener = refreshListener;
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable parcelable = super.onSaveInstanceState();
        SavedState savedState = new SavedState(parcelable);
        savedState.state = this.displayState;
        return savedState;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        this.displayState = savedState.state;
        setDisplayState(this.displayState, fragmentType);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_error_retry || i == R.id.btn_empty_retry) {
            setDisplayState(STATE_LOADING, fragmentType);
            currentPage = 1;
            if(refreshListener != null){
                refreshListener.onRefresh(true);
            }
        }
    }

    public static interface OnRefreshListener {
        void onRefresh(boolean fromSwipe);
    }

    public static interface OnMoreListener {
        void onMore(int page);
    }


    static class SavedState extends BaseSavedState {
        private int state;

        SavedState(Parcelable superState) {
            super(superState);
        }

        public SavedState(Parcel source) {
            super(source);
            try {
                state = source.readInt();
            } catch (IllegalArgumentException e) {
                state = STATE_LOADING;
            }
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(state);
        }

        public static final Creator<SavedState> CREATOR =
                new Creator<SavedState>() {
                    @Override
                    public SavedState createFromParcel(Parcel in) {
                        return new SavedState(in);
                    }

                    @Override
                    public SavedState[] newArray(int size) {
                        return new SavedState[size];
                    }
                };
    }

}
